from wtforms import StringField, TextAreaField
from wtforms.validators import Optional, ValidationError, DataRequired

from apps.forms.base_form import BaseForm
from common.oss_upload import get_file_url
from rules.image_library_rule import search_image_library_by_title


class QueryImageLibraryForm(BaseForm):
    title = StringField('标题', validators=[Optional()], render_kw={"placeholder": "标题", 'class': 'search-input'})
    dy_open_pic_id = StringField('抖音图片id', validators=[Optional()],
                                 render_kw={"placeholder": "抖音图片id", 'class': 'search-input'})


class CreateImageLibraryForm(BaseForm):
    title = StringField('标题', validators=[DataRequired(message='请填写标题')],
                        render_kw={"placeholder": "请填写标题"})
    file_name = StringField('图片素材', validators=[DataRequired(message='请上传图片')])
    remarks = TextAreaField('备注', validators=[Optional()])

    def validate_title(self, field):
        model_orm = search_image_library_by_title(field.data)
        if model_orm:
            raise ValidationError('标题已存在')


class UpdateImageLibraryForm(BaseForm):
    title = StringField('标题', validators=[DataRequired(message='请填写标题')],
                        render_kw={"placeholder": "请填写标题"})
    file_name = StringField('图片名称', validators=[DataRequired(message='请上传图片')])
    file_url = StringField('图片地址', validators=[Optional()])
    remarks = TextAreaField('备注', validators=[Optional()])

    def __init__(self, model_orm=None, *args, **kwargs):
        super(UpdateImageLibraryForm, self).__init__(*args, **kwargs)
        if model_orm:
            self.title.data = model_orm.title
            self.file_name.data = model_orm.file_name
            self.file_url.data = get_file_url(model_orm.file_name)
            self.remarks.data = model_orm.remarks
